package com.lagou.rpc.provider.util;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZkUtil {
    private static ZkClient zkClient = null;

    /**
     * 根目录
     */
    private static final String PARENT_PATH = "/netty";

    /**
     * 本地储存
     */
    private static final Map<String, String> CHILDREN_NODE_MAP = new HashMap<>(16);

    public ZkUtil() {
        connect();
    }

    public static ZkClient connect() {

        zkClient = new ZkClient("127.0.0.1:2181");

        System.out.println("zk连接建立");

        //建立初始节点
        //判断是否存在
        boolean exists = zkClient.exists(PARENT_PATH);
        if(!exists) {
            //节点不存在，创建永久节点
            zkClient.createPersistent(PARENT_PATH);
        }

        return zkClient;
    }


    public void createNode(String path, String value) {

        CHILDREN_NODE_MAP.put(path, value);

        path = PARENT_PATH + path;

        //创建临时节点
        zkClient.createEphemeral(path);
        System.out.println("zk创建节点" + path);
        zkClient.writeData(path, value);
        System.out.println("节点" + path + " 写入值 " + value);

        //注册监听,监听子节点
        zkClient.subscribeChildChanges(PARENT_PATH, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> list) throws Exception {
                System.out.println("该节点子节点内容发生更新");
            }
        });

        //注册监听
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println(s + "该节点内容被更新，更新的内容" + o);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s + "该节点被删除");
            }
        });
    }
}
